package com.dolphin.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.dolphin.common.constant.TokenConstants;
import com.dolphin.common.dto.TokenResult;
import com.dolphin.common.util.JwtUtils;
import com.dolphin.common.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    PathInterceptorConfig pathInterceptorConfig;
    List<String> authPath;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        authPath = pathInterceptorConfig.getExcludePathPatterns();

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        log.info(path + "请求来了");

        boolean flag = true;
        String result = "";

        if (!authPath.contains(path)) {
            log.info("需要校验");
//            request.getHeaders()
            String token = request.getHeaders().getFirst("Authorization");
            TokenResult tokenResult = JwtUtils.checkToken(token);
            if (tokenResult == null) {
                result = "access token invalid";
                flag = false;
            } else {
                String phone = tokenResult.getPhone();
                String identity = tokenResult.getIdentity();

                String tokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity, TokenConstants.ACCESS_TOKEN);
                String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
                if (StringUtils.isBlank(tokenRedis) || !token.trim().equals(tokenRedis)) {
                    result = "access token invalid";
                    flag = false;
                }
            }
        } else {
            log.info("不需要校验");
        }

        if (!flag) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        return chain.filter(exchange);
    }
}
